package com.rx.mgt.service;

import com.rx.mgt.dao.RuleDao;
import com.rx.mgt.dao.RuleDetailDao;
import com.rx.mgt.domain.EmailRuleDetailDomain;
import com.rx.mgt.domain.EmailRuleDomain;
import com.rx.mgt.util.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by zxj on 2017/8/15.
 */
@Service
@Transactional
public class RuleService {
    @Autowired
    private RuleDao dao;
    @Autowired
    private RuleDetailDao detailDao;
    public List<EmailRuleDomain> queryAll() {
        return dao.list();
    }

    public void save(EmailRuleDomain ruleDomain) {
        String id = StringUtil.UUID();
        ruleDomain.setId(id);
        List<EmailRuleDetailDomain> ruleDetailDomainList = ruleDomain.getRuleDetailDomainList();
        for(int i=0;i<ruleDetailDomainList.size();i++){
            EmailRuleDetailDomain detailDomain = ruleDetailDomainList.get(i);
            if(StringUtils.isNotBlank(detailDomain.getRulevalue())){
                detailDomain.setRx_rule_id(id);
                detailDao.save(detailDomain);
            }else{
                ruleDetailDomainList.remove(i);
            }

        }
        dao.save(ruleDomain);
    }

    public EmailRuleDomain queryRuleById(String id) {
        EmailRuleDomain domain = dao.get(id);
        List<EmailRuleDetailDomain> list = detailDao.find("from EmailRuleDetailDomain e where e.rx_rule_id=?",id);
        domain.setRuleDetailDomainList(list);
        return domain;
    }

    public void deleteRuleById(String id) {
        EmailRuleDomain domain = dao.get(id);
        dao.delete(domain);
        detailDao.deleteAll(detailDao.find("from EmailRuleDetailDomain e where e.rx_rule_id=?",id));

    }

    public void update(EmailRuleDomain ruleDomain) {
        dao.update(ruleDomain);
        String rx_rule_id = ruleDomain.getId();
        List<EmailRuleDetailDomain> ruleDetailDomainList = ruleDomain.getRuleDetailDomainList();
        detailDao.deleteAll(detailDao.find("from EmailRuleDetailDomain e where e.rx_rule_id=?",rx_rule_id));
        for(int i=0;i<ruleDetailDomainList.size();i++){
            EmailRuleDetailDomain detailDomain = ruleDetailDomainList.get(i);
            if(StringUtils.isNotBlank(detailDomain.getRulevalue())){
                detailDomain.setRx_rule_id(rx_rule_id);
                detailDao.saveOrUpdate(detailDomain);
            }else{
                ruleDetailDomainList.remove(i);
            }

        }
    }
}
